/**
 * 压缩图片
 * @param {Object} file - 文件对象
 * @param {Object} options - 压缩选项
 * @param {number} options.quality - 压缩质量 (0-1)
 * @param {number} options.maxWidth - 最大宽度
 * @param {number} options.maxHeight - 最大高度
 * @returns {Promise<File>} - 返回压缩后的文件
 */
export const compressImage = (file, options = {}) => {
	return new Promise((resolve, reject) => {
		const {
			quality = 0.7, maxWidth = 720, maxHeight = 1080
		} = options;

		// 如果是H5环境
		if (process.env.VUE_APP_PLATFORM === "h5") {
			const reader = new FileReader();
			reader.onload = (event) => {
				const img = new Image();
				img.onload = () => {
					const canvas = document.createElement("canvas");
					let width = img.width;
					let height = img.height;

					// 计算缩放比例
					if (width > maxWidth || height > maxHeight) {
						const ratio = Math.min(maxWidth / width, maxHeight / height);
						width *= ratio;
						height *= ratio;
					}

					canvas.width = width;
					canvas.height = height;

					const ctx = canvas.getContext("2d");
					ctx.drawImage(img, 0, 0, width, height);

					canvas.toBlob(
						(blob) => {
							const compressedFile = new File([blob], file.name, {
								type: file.type,
								lastModified: Date.now()
							});
							resolve(compressedFile);
						},
						file.type,
						quality
					);
				};
				img.onerror = reject;
				img.src = event.target.result;
			};
			reader.onerror = reject;
			reader.readAsDataURL(file.file);
		}
		// 如果是小程序环境
		else {
			uni.compressImage({
				src: file.path || file.url,
				quality: quality * 100,
				success: (res) => {
					// 在小程序中，压缩后返回的是临时路径
					// 需要转换为File对象（在H5中）或保持临时路径（在小程序中）
					if (process.env.VUE_APP_PLATFORM === "h5") {
						// H5环境下需要将临时路径转换为File对象
						uni.uploadFile({
							url: res.tempFilePath,
							fileType: "image",
							success: (uploadRes) => {
								resolve(uploadRes.tempFiles[0]);
							},
							fail: reject
						});
					} else {
						// 小程序环境下直接使用临时路径
						resolve({
							...file,
							path: res.tempFilePath
						});
					}
				},
				fail: reject
			});
		}
	});
};